package org.lc.stk.dao.bank;

import java.util.Optional;

import org.lc.stk.model.banks.PaperBank;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

public interface PaperBankRepository extends JpaRepository<PaperBank, Integer> {
    
    /**
     * 检查名称是否存在
     */
    @Query("SELECT COUNT(b) > 0 FROM PaperBank b WHERE b.name = :name AND (:excludeId IS NULL OR b.id != :excludeId)")
    boolean existsByNameAndIdNot(
        @Param("name") String name,
        @Param("excludeId") Integer excludeId
    );

    /**
     * 分页查询
     */
    @Query("SELECT b FROM PaperBank b WHERE " +
           "(:name IS NULL OR b.name LIKE %:name%) AND " +
           "(:state IS NULL OR b.state = :state)")
    Page<PaperBank> findByConditions(
        @Param("name") String name,
        @Param("state") Integer state,
        Pageable pageable
    );

    /**
     * 根据试卷模板ID查询试卷库
     */
    @Query("SELECT DISTINCT b FROM PaperBank b JOIN b.paperTemplates t WHERE t.id = :templateId")
    Optional<PaperBank> findByTemplateId(@Param("templateId") Integer templateId);
}